package zhxt.helmet.controller;

import org.bytedeco.opencv.opencv_core.*;
import org.bytedeco.opencv.opencv_imgproc.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import zhxt.helmet.service.Yolov10Service;
import zhxt.helmet.utils.FrameToMatConverter;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/detect")
public class DetectController {
    @Autowired
    private Yolov10Service yolov10Service;
    @RequestMapping(value = "/yolov10detect", produces = "text/html;charset=UTF-8")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> yolov10detect(@RequestParam("image") MultipartFile imageFile) {
        Map<String, Object> response = new HashMap<>();
        try {
            // 1. 检查文件有效性
            if (imageFile.isEmpty()) {
                throw new IllegalArgumentException("请选择图片文件");
            }

            // 2. 将MultipartFile转换为OpenCV的Mat对象
            Mat image = convertMultipartFileToMat(imageFile);
            //System.out.println("Mat type: "+ CvType.typeToString(image.type()));
            //FrameToMatConverter.saveMatToFile(image,"output.jpg");//保存图片看看输入数据是否正常

            // 3. 调用YOLO识别服务
            List<Map<String, Object>>  boxes = yolov10Service.detect(image);

            // 5. 返回结果
            response.put("success", true);
            response.put("boxes", boxes);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", e.getMessage());
            e.printStackTrace();
        }
        return ResponseEntity.ok().contentType(MediaType.APPLICATION_JSON).body(response);
    }
    // 将MultipartFile转换为OpenCV Mat（使用org.bytedeco的OpenCV库）
    private Mat convertMultipartFileToMat(MultipartFile file) throws IOException {
        byte[] bytes = file.getBytes();
        Mat mat = org.bytedeco.opencv.global.opencv_imgcodecs.imdecode(new Mat(bytes), org.bytedeco.opencv.global.opencv_imgcodecs.IMREAD_COLOR);
        if (mat.empty()) {
            throw new IOException("无法解析图片文件");
        }
        return mat;
    }
}
